<?php
namespace app\admin\controller;

use think\Request;
use think\Config;
use app\common\controller\Common;
use app\common\model\Config as ConfigModel;

class Admin extends Common
{
    /**
     * 获取模版目录列表
     *
     * @return array
     */
    public function getTheme() {
        $dir = ROOT_PATH . 'theme';
        $dirArray[] = NULL;
        if (false != ($handle = opendir( $dir ))) {
            $i=0;
            while ( false !== ($file = readdir ( $handle )) ) {
                //去掉"“.”、“..”以及“.*”后缀的文件
                if ($file != "." && $file != ".." && !strpos($file, ".")) {
                    $path = ROOT_PATH . 'theme' . DS . $file . DS . 'screenshot.png';
                    $logo = 'theme' . DS . $file . DS . 'screenshot.png';
                    $dirArray[$i]['name'] = $file;
                    $dirArray[$i]['logo'] = file_exists($path) ? buildImageUrl($logo) : defaultImageUrl();
                    $i++;
                }
            }
            //关闭句柄
            closedir($handle);
        }
        return $dirArray;
    }
    
    /**
     * 扫描目录中的文件
     *
     * @params $dir string 目录
     * @return array
     */
    public function my_scandir($dir)
    {
        $files = array();

        if (is_dir($dir)) {
            if($handle = opendir($dir)) {
                while(($file = readdir($handle)) !== false) {
                    if($file != "." && $file != "..") {
                        if (is_dir($dir . "/" . $file)) {
                            $files = $this->my_scandir($dir . "/" . $file);
                        }
                        else {
                            $files[] = $dir . "/" . $file;
                        }
                    }
                 }
                closedir($handle);
            }
        }

        return $files;
    }

    /** 
     * 获取目录下模版文件
     *
     * @return array
     */
    public function templateList()
    {
        $theme = $this->config('theme');
        $dir   = ROOT_PATH . 'theme' . DS . $theme;
        $list  = $this->my_scandir($dir);

        $new_list = array();
        if (!empty($list)) {
            foreach ($list as $v){
               $arr = explode(".", $v);
               // 过滤模版文件
               if ($arr[1] == 'html') {
                   $len = strlen($arr[0]);
                   $tp = strpos($arr[0], $theme);
                   $str = substr($arr[0], $tp + strlen($theme) + 1, $len);
                   array_push($new_list, $str);
               }
            }
        }

       return $new_list;
    }

}
